package com.motu.monstercity.server.game.timedtask;

import com.motu.monstercity.server.game.commondata.act.Act;
import com.motu.monstercity.server.game.commondata.act.ActConstant;
import com.motu.monstercity.server.game.logic.ActConventionManager;
import com.motu.monstercity.server.game.logic.ActManager;
import com.motu.monstercity.server.game.logic.UnionMobileManager;
import com.motu.monstercity.server.game.logic.UnionScuffleManager;
import com.motu.vertx.module.utility.threadpool.DBLogManager;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.json.JsonObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

public class ActEndTask implements Runnable, Delayed {

	public final static Logger logger = LoggerFactory.getLogger(ActEndTask.class);

	private long actId; // 活动ID
	private int actType; // 活动类型
	private String param; // 额外参数(主题活动结算任务有用)
	private long execTime; // 任务执行时间

	public ActEndTask(long actId, int actType, long execTime, String param) {
		this.actId = actId;
		this.actType = actType;
		this.execTime = execTime;
		this.param = param;
	}

	@Override
	public void run() {
		JsonObject jsonObject = new JsonObject();
		jsonObject.put("actId", actId);
		jsonObject.put("actType", actType);
		jsonObject.put("param", param);
		TimedTaskManager.sendWorkTask(TimeTaskCmd.WORK_ACT_END, jsonObject);
	}

	public static void runTask(JsonObject jsonObject) {
		long actId = jsonObject.getLong("actId");
		int actType = jsonObject.getInteger("actType");
		String param = jsonObject.getString("param");
		try {
			logger.info("### end act id = " + actId + " actType = " + actType + " param = " + param);
			Act act = ActManager.getAct(actId);
			if (act == null) {
				return;
			}
			if (act.getType() == Act.ACT_TYPE_SEVEN_DAYS) {
//				ActDaysManager.doSevenDaysActEndLogic(act);
			} else if (act.getType() == ActConstant.ACT_TYPE_UNION_SCUFFLE) {
				UnionScuffleManager.clearActData(act);
			} else if (act.getType() == ActConstant.ACT_TYPE_1002){
				UnionMobileManager.clearActData(act);
			}
		} catch (Exception e) {
			String errMsg = Tool.getException(e);
			logger.error(errMsg);
			DBLogManager.addServerCrashLog(actId, errMsg);
		}
	}

	@Override
	public long getDelay(TimeUnit unit) {
		return unit.convert(execTime - TimeUtils.getCurTime(), TimeUnit.SECONDS);
	}

	@Override
	public int compareTo(Delayed o) {
		ActEndTask that = (ActEndTask) o;
		return execTime > that.execTime ? 1 : (execTime < that.execTime ? -1 : 0);
	}

	public long getActId() {
		return this.actId;
	}

	public long getExecTime() {
		return this.execTime;
	}

}
